from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from . import mail





def send_async_email(app, msg):
	# 异步发送邮件
	with app.app_context():
		mail.send(msg)

def send_email(to, subject, template, **kwargs):
	app = current_app._get_current_object()
	#定义send_email（）函数的参数分别是收件箱地址，主题，渲染邮件正文的模板和关键字参数
	msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
					sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
	#为了能够发送邮件，首先需要创建一个 Message 实例，里面配置了主题前缀，发送人邮件地址，接收人
	msg.body = render_template(template + '.txt', **kwargs)
	msg.html = render_template(template + '.html', **kwargs)
	thr = Thread(target=send_async_email, args=[app, msg])
	thr.start()
	return thr